/*
    BEEM is a videoconference application on the Android Platform.

    Copyright (C) 2009 by Frederic-Charles Barthelery,
                          Jean-Manuel Da Silva,
                          Nikita Kozlov,
                          Philippe Lago,
                          Jean Baptiste Vergely,
                          Vincent Veronis.

    This file is part of BEEM.

    BEEM is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    BEEM is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with BEEM.  If not, see <http://www.gnu.org/licenses/>.

    Please send bug reports with examples or suggestions to
    contact@beem-project.com or http://dev.beem-project.com/

    Epitech, hereby disclaims all copyright interest in the program "Beem"
    written by Frederic-Charles Barthelery,
               Jean-Manuel Da Silva,
               Nikita Kozlov,
               Philippe Lago,
               Jean Baptiste Vergely,
               Vincent Veronis.

    Nicolas Sadirac, November 26, 2009
    President of Epitech.

    Flavien Astraud, November 26, 2009
    Head of the EIP Laboratory.

*/
package com.spice.im;

//import android.os.AsyncTask;

//import com.isharemessage.provider.plugin.EncryptionUtil;

import org.afinal.simplecache.ACache2;



import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;

import com.speed.im.login.EncryptionUtil;
//import com.speed.im.login.LoginIQ;
//import com.speed.im.login.LoginIQResponse;
//import com.speed.im.login.LoginIQResponseProvider;
import com.spice.im.utils.AsyncTask;
import com.spice.im.utils.StringUtils;
import com.spiceim.db.TContactGroupAdapter;
import com.spring4jchome.encrypt.utils.Base64URLEncodeTool;
import com.stb.core.chat.ContactGroup;
import com.stb.core.chat.RosterAdapter;
import com.stb.isharemessage.BeemApplication;
import com.stb.isharemessage.service.aidl.IXmppConnection;
import com.stb.isharemessage.service.aidl.IXmppFacade;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.RemoteException;
import android.preference.PreferenceManager;





import android.util.Log;
//import com.stb.isharemessage.service.aidl.IXmppConnection;
//import com.stb.isharemessage.service.aidl.IXmppFacade;
//import com.example.android.bitmapfun.util.AsyncTask;
//import com.speed.im.utils.AsyncTask;
//import com.speed.im.utils.AsyncTask.Status;
import android.widget.Toast;

/**
 * This is an asynchronous task that will launch a connection to the XMPP server.
 * @see android.os.AsyncTask
 * @author Da Risk <da_risk@elyzion.net>
 */
public class LoginAsyncTask extends AsyncTask<IXmppFacade, Integer, Boolean> {

    /**
     * State of a running connection.
     */
    public static final int STATE_CONNECTION_RUNNING = 0;
    /**
     * State of an already connected connection but authentication is running.
     */
    public static final int STATE_LOGIN_RUNNING = 1;
    /**
     * State of a connected and authenticated succesfully.
     */
    public static final int STATE_LOGIN_SUCCESS = 2;
    /**
     * State of a connected but failed authentication.
     */
    public static final int STATE_LOGIN_FAILED = 3;

    private static final String TAG = "BeemLoginTask";

    private IXmppConnection mConnection;
    private String mErrorMessage;
    
    private Context mContext;
    private TContactGroupAdapter tContactGroupAdapter = null;
    
    public void setMContext(Context context){
    	mContext = context;
    	mCache = ACache2.get(mContext);
    	tContactGroupAdapter = TContactGroupAdapter.getInstance(mContext);
    }
    public Context getMContext(){
    	return mContext;
    }
    private ACache2 mCache;
    /**
     * Constructor.
     */
    public LoginAsyncTask() {
    }

	private String[] errorMsg = new String[]{"抱歉,没有找到相关结果.",
			"服务连接中1-1,请稍候再试.",
			"服务连接中1-2,请稍候再试.",
			"服务连接中1-3,请稍候再试.",
			"网络连接不可用,请检查你的网络设置.",
			"",
			"链接服务器网络或手机信号不好,请求异常,稍候重试!",
			"已登录，无需重复登录!",
			"登录用户名userName不能为空",
			"登录失败，用户名userName错误",
			"登录失败，密码错误",
			"登录失败,hash校验失败"};
	
	//IXmppFacade... params表示的是可变参数列表,也就是说,这样的方法能够接受的参数个数是可变的,但不论多少,必须都是IXmppFacade类型的
    @Override
    protected Boolean doInBackground(IXmppFacade... params) {
	boolean result = true;
	IXmppFacade mXmppFacade = params[0];
	try {
	    publishProgress(STATE_CONNECTION_RUNNING);
//	    mXmppFacade.getXmppConnectionAdapter();
	    mConnection = mXmppFacade.createConnection();
	    if (!mConnection.connect()) {
		mErrorMessage = mConnection.getErrorMessage();
		return false;
	    }
	    publishProgress(STATE_LOGIN_RUNNING);

//	    if (!mConnection.login()) {
//		mErrorMessage = mConnection.getErrorMessage();
//		publishProgress(STATE_LOGIN_FAILED);
//		return false;
//	    }
	    //业务登录start
	    try {
	    	if(mXmppFacade!=null){
		    	if (mXmppFacade.getXmppConnectionAdapter()!=null 
						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null
						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected() 
						&& mXmppFacade.getXmppConnectionAdapter().login()//注意，第三方登陆login之前，需要调用框架本身的auth接口
//		    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated() //登录成功后才会startService，因此登录时不要判断isAuthenticated及isAlive
//		    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
		    			){
		    		//注意这里的第三方login登陆：loginiq com:isharemessage:loginiq
		    		//框架本身的auth接口：query jabber:iq:auth   对应mXmppFacade.getXmppConnectionAdapter().login()方法
//		    		LoginIQ reqXML = new LoginIQ();
//		            reqXML.setId("1234567890");
//		            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
//		    	    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getMContext());
//		    	    String login = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
//		    	    String password = settings.getString(BeemApplication.ACCOUNT_PASSWORD_KEY, "");
//		            reqXML.setUsername(login);
//		            reqXML.setPassword(password);
//		            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(getMContext());
//		            reqXML.setUuid(uuid);
//		            
//		            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ "admin"+uuid;
//		            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
//		            reqXML.setHash(hash_dest);
//		            reqXML.setType(IQ.Type.SET);
//		            String elementName = "loginiq"; 
//		    		String namespace = "com:isharemessage:loginiq";
//		    		LoginIQResponseProvider provider = new LoginIQResponseProvider();
//		            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "loginiq", "com:isharemessage:loginiq", provider);
//		            
//		            if(rt!=null){
//		                if (rt instanceof LoginIQResponse) {
//		                	final LoginIQResponse loginIQResponse = (LoginIQResponse) rt;
//
//		                    if (loginIQResponse.getChildElementXML().contains(
//		                            "com:isharemessage:loginiq")) {
////		    					TestActivity.this.runOnUiThread(new Runnable() {
////			                    	
////        							@Override
////        							public void run() {
////        								showCustomToast("服务器应答消息："+advancedSearchIQResponse.toXML().toString());
////        							}
////        						});
//		                        String Id = loginIQResponse.getId();
//		                        String retcode = loginIQResponse.getRetcode();
//		                        String memo = loginIQResponse.getMemo();
//		                        String sessionid = loginIQResponse.getSessionid();
//		                        sessionid = Base64URLEncodeTool.decodeBase64URLUserInfo(sessionid);
//		                        String uid = loginIQResponse.getUid();
//		                        if(retcode.equals("0000")){
//		                        	mCache.put("sessionid", sessionid);
//		                        	BeemApplication.getInstance().setConnected(true);
//		                        	mXmppFacade.getXmppConnectionAdapter().setJID(uid+"@"+"0"+"/"+login);
//		                        	Log.d("####LoginAsyncTask####", "JID="+mXmppFacade.getXmppConnectionAdapter().getJID());
//		                        }else if(retcode.equals("0001")){
//		                        	BeemApplication.getInstance().setConnected(false);
//		                        	mErrorMessage = errorMsg[7];
//		    		        		publishProgress(STATE_LOGIN_FAILED);
//		    		        		return false;
//		                        }else if(retcode.equals("0002")){
//		                        	BeemApplication.getInstance().setConnected(false);
//		                        	mErrorMessage = errorMsg[8];
//		    		        		publishProgress(STATE_LOGIN_FAILED);
//		    		        		return false;
//		                        }else if(retcode.equals("0003")){
//		                        	BeemApplication.getInstance().setConnected(false);
//		                        	mErrorMessage = errorMsg[9];
//		    		        		publishProgress(STATE_LOGIN_FAILED);
//		    		        		return false;
//		                        }else if(retcode.equals("0004")){
//		                        	BeemApplication.getInstance().setConnected(false);
//		                        	mErrorMessage = errorMsg[10];
//		    		        		publishProgress(STATE_LOGIN_FAILED);
//		    		        		return false;
//		                        }else if(retcode.equals("9998") || retcode.equals("9999")){
//		                        	BeemApplication.getInstance().setConnected(false);
//		                        	mErrorMessage = memo;
//		    		        		publishProgress(STATE_LOGIN_FAILED);
//		    		        		return false;
//		                        }
//		                    }else{
//		                    	BeemApplication.getInstance().setConnected(false);
//		                    	mErrorMessage = errorMsg[6];
//				        		publishProgress(STATE_LOGIN_FAILED);
//				        		return false;
//		                    }
//		                }else{
//		                	BeemApplication.getInstance().setConnected(false);
//	                    	mErrorMessage = errorMsg[6];
//			        		publishProgress(STATE_LOGIN_FAILED);
//			        		return false;
//		                } 
//		            }else{
//		            	BeemApplication.getInstance().setConnected(false);
//		        		mErrorMessage = errorMsg[6];
//		        		publishProgress(STATE_LOGIN_FAILED);
//		        		return false;
//		            }
		    		
		    		String retcode = mXmppFacade.getXmppConnectionAdapter().ThirdPartnerLogin4RosterInitial();
//		    		//为了测试登录接口性能 start 20171104
//		    		String retcode = "0000";
//		    		String uid = "17";
//                	BeemApplication.getInstance().setConnected(true);
//                	mXmppFacade.getXmppConnectionAdapter().setJID(uid+"@"+"0"+"/"+"admin");
//                	
//                	mXmppFacade.getXmppConnectionAdapter().mRoster = null;
//                	mXmppFacade.getXmppConnectionAdapter().getAdaptee().getConfiguration().setRosterLoadedAtLogin(false);//第一次登录时加载roster，后续无需加载
//                	mXmppFacade.getXmppConnectionAdapter().mRoster = new RosterAdapter(mXmppFacade.getXmppConnectionAdapter().getAdaptee().getRoster(), 
//                			mXmppFacade.getXmppConnectionAdapter().getAdaptee().getMService());
//                	mXmppFacade.getXmppConnectionAdapter().getAdaptee().getConfiguration().setRosterLoadedAtLogin(true);
//                	//为了测试登录接口性能 end 20171104
                	
		    		if(retcode!=null){
		    			if(retcode.startsWith("0000")){
                        	Log.d("####20170811LoginAsyncTask####", "20170811LoginAsyncTask JID="+mXmppFacade.getXmppConnectionAdapter().getJID());
                        	Log.d("####20170811LoginAsyncTask####", "20170811LoginAsyncTask Name="+mXmppFacade.getXmppConnectionAdapter().getName());
                        	ContactGroup contactGroup = new ContactGroup(mXmppFacade.getXmppConnectionAdapter().getJID());//登录成功用户个人信息存储到本地sqlite
                        	contactGroup.setName(mXmppFacade.getXmppConnectionAdapter().getName());
                        	contactGroup.setAvatar(mXmppFacade.getXmppConnectionAdapter().getAvatar());
                        	contactGroup.setAvatarPath(mXmppFacade.getXmppConnectionAdapter().getAvatarpath());
                        	//contactGroup.setSex(mSex);
                        	
                        	
//                        	Toast toast = Toast.makeText(mContext, "我的contactGroup="+contactGroup.toXML()+"头像avatar="+contactGroup.getAvatar()+";avatarpath="+contactGroup.getAvatarPath(), Toast.LENGTH_LONG);
//    			    	    toast.show();
                        	Log.d("####20200315LoginAsyncTask存入sqllite前####", "20200315LoginAsyncTask Name="+"我的contactGroup="+contactGroup.toXML()+"头像avatar="+contactGroup.getAvatar()+";avatarpath="+contactGroup.getAvatarPath());
//                        	tContactGroupAdapter.addTContactGroup(contactGroup,StringUtils.parseName(mXmppFacade.getXmppConnectionAdapter().getJID()));
                        	tContactGroupAdapter.addTContactGroup(contactGroup,StringUtils.parseBareAddress(mXmppFacade.getXmppConnectionAdapter().getJID()));
                        	Log.d("####20200315LoginAsyncTask存入sqllite后####", "20200315LoginAsyncTask key="+StringUtils.parseBareAddress(mXmppFacade.getXmppConnectionAdapter().getJID())+";value="+tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mXmppFacade.getXmppConnectionAdapter().getJID())).toXML()+";avatarpath="+tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mXmppFacade.getXmppConnectionAdapter().getJID())).getAvatarPath());
//                        	Log.d("####20171220LoginAsyncTask####", "20171220LoginAsyncTask TContactGroup="+tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mXmppFacade.getXmppConnectionAdapter().getJID())).toXML());
                            
                        	//更新本地
                        	SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
				    		SharedPreferences.Editor edit = settings.edit();
////				    		edit.putString(BeemApplication.ACCOUNT_USERNAME_KEY, mActivity.username+"@pc2011040521xsg");
//				    		edit.putString(BeemApplication.ACCOUNT_USERNAME_KEY, username);
//				    		edit.putString(BeemApplication.ACCOUNT_PASSWORD_KEY, password);
				    		edit.putString("uidStr", StringUtils.parseName(mXmppFacade.getXmppConnectionAdapter().getJID()));
				    		edit.putString("uidStr"+settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, ""), StringUtils.parseName(mXmppFacade.getXmppConnectionAdapter().getJID()));
				    		edit.commit();
                        	
		    			}else if(retcode.startsWith("0001")){
                        	mErrorMessage = errorMsg[7];
    		        		publishProgress(STATE_LOGIN_FAILED);
    		        		return false;
                        }else if(retcode.startsWith("0002")){
                        	mErrorMessage = errorMsg[8];
    		        		publishProgress(STATE_LOGIN_FAILED);
    		        		return false;
                        }else if(retcode.startsWith("0003")){
                        	mErrorMessage = errorMsg[9];
    		        		publishProgress(STATE_LOGIN_FAILED);
    		        		return false;
                        }else if(retcode.startsWith("0004")){
                        	mErrorMessage = errorMsg[10];
    		        		publishProgress(STATE_LOGIN_FAILED);
    		        		return false;
                        }else if(retcode.startsWith("0005")){
                        	mErrorMessage = errorMsg[11];
    		        		publishProgress(STATE_LOGIN_FAILED);
    		        		return false;
                        }else if(retcode.startsWith("9998") || retcode.startsWith("9999")){
                        	mErrorMessage = retcode;
    		        		publishProgress(STATE_LOGIN_FAILED);
    		        		return false;
                        }
		    		}else{
		    			mErrorMessage = errorMsg[6];
		        		publishProgress(STATE_LOGIN_FAILED);
		        		return false;
		    		}
		    	}else{
		    		BeemApplication.getInstance().setConnected(false);
		    		mErrorMessage = errorMsg[1];
	        		publishProgress(STATE_LOGIN_FAILED);
	        		return false;
		    	}
	    	}else{
	    		BeemApplication.getInstance().setConnected(false);
	    		mErrorMessage = errorMsg[2];
        		publishProgress(STATE_LOGIN_FAILED);
        		return false;
	    	}
			
	    } catch (RemoteException e) {
	    	e.printStackTrace();
	    	BeemApplication.getInstance().setConnected(false);
	    	mErrorMessage = errorMsg[3];
    		publishProgress(STATE_LOGIN_FAILED);
    		return false;
	    	
	    	
	    } catch (Exception e){
	    	BeemApplication.getInstance().setConnected(false);
	    	mErrorMessage = errorMsg[3];
    		publishProgress(STATE_LOGIN_FAILED);
    		return false;
	    }
	    //业务登录end
	    
	    
	    publishProgress(STATE_LOGIN_SUCCESS);
	} catch (Exception e) {
	    mErrorMessage = "Exception during connection :" + e;
	    result = false;
	}
	return result;
    }

    /**
     * Make sur to call the parent method when overriding this method.
     */
    @Override
    protected void onCancelled() {
	try {
//	    if (mConnection != null && mConnection.isAuthentificated()) {
//		mConnection.disconnect();
//	    }
	} catch (Exception e) {
	    Log.d(TAG, "Remote exception", e);
	}
    }

    /**
     * Get the error Message.
     * @return the error message. null if no error
     */
    public String getErrorMessage() {
	return mErrorMessage;
    }
}
